from code_builder.tools import utils,create_file_name
from code_builder.templet import read_temp_file

def create_insert_code(data):
    result = read_temp_file.read_jsp_insert()
    tr = tr_builder(data)
    return result.format(page_title="新增",action="doInsert",tr=tr)


def create_update_code(data):
    result = read_temp_file.read_jsp_insert()
    tr = tr_builder(data)
    return result.format(page_title="更新",action="doUpdate",tr=tr)

def tr_builder(data):
    result = ""
    for i in range(1,len(data)-3,2):
        if i!= len(data)-3:
            result += "<tr><td>{0}:</td><td><input name=\"{1}\"></td><td>{2}:</td><td><input name=\"{3}\"></td></tr>".format(data[i]['field_name'],
                                                                                                                             utils.to_low_camel_case(data[i]['field_code']), data[i + 1]['field_name'],
                                                                                                                             utils.to_low_camel_case(data[i + 1]['field_code']))
        else:
            result += "<tr><td>{0}:</td><td><input name=\"{1}\"></td><td></td><td></td></tr>".format(data[i]['field_name'],
                                                                                                     utils.to_low_camel_case(data[i]['field_code']))
    return result

def create_jsp_file(data,target_path,table_name):
    create_insert_file(data, target_path, table_name)
    create_update_file(data, target_path, table_name)

def create_insert_file(data,target_path,table_name):
    insert_data = create_insert_code(data)
    insert_jsp_file_name = create_file_name.jsp_insert_name(table_name)
    create_insert_file_isSuccess = utils.create_file(target_path, insert_jsp_file_name, insert_data)
    if create_insert_file_isSuccess:
        utils.print_create_success(insert_jsp_file_name)

def create_update_file(data,target_path,table_name):
    update_data = create_update_code(data)
    update_jsp_file_name = create_file_name.jsp_update_name(table_name)
    create_update_file_isSuccess = utils.create_file(target_path, update_jsp_file_name, update_data)
    if create_update_file_isSuccess:
        utils.print_create_success(update_jsp_file_name)
